<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class TestController extends Controller
{
    
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);
        
        $request['password'] = bcrypt($request->password);
        User::create($request->all());
        return response()->json(
            [
                'success' => 'ok'
            ],
            201
        );
    }
    
    /**
     * will return a token like
     * aqWB1ww62kCKpVENhi4l6OLmmcxADw2oQvwF4h2wNgUC4vyc35w4HOWi1X8sJjRswBhOmdsM59q4Hjiz
     *
     * and give a right of article:edit
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        $request->validate(
            [
                'email' => 'required|email',
                'password' => 'required'
            ]
        );
        
        $user = User::where('email', $request->email)->first();
        if (!$user || Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'email' => ['the provider credentials are incorrect. ']
            ]);
        }
        return $user->createToken($request->email, ['article:edit'])->plainTextToken;
    }
    
    public function editArticle(Request $request)
    {
        $response = 'no';
        if ($request->user()->tokenCan('article:edit')) {
            $response = 'yes';
        }
        return response()->json(
            [
                'response' => $response
            ],
            201
        );
    }
    
    public function logout(Request $request)
    {
        if ($request->user()->tokens()) {
            $request->user()->tokens()->delete();
        }
        return response()->json(
            [
                'deleted' => true
            ],
            201
        );
    }
}
